package com.example.jussi.sharedpreferencesdemo;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 通过 SharedPreferences 来储存数据
 */

public class MainActivity extends AppCompatActivity {
    TextView textView;
    EditText editText;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView2);
        editText = (EditText) findViewById(R.id.editText);
        sharedPreferences = getSharedPreferences("jussi", Context.MODE_WORLD_READABLE);
        editor = sharedPreferences.edit();
    }

    public void save(View hhView){
        editor.putString("001", editText.getText().toString());
        editor.commit();    //设置值之后，一定要记得提交，否则无效
    }

    public void read(View hhView){
        String string = sharedPreferences.getString("001", "Null");
        textView.setText(string);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //editor.clear();   //如果自己不删除的话，永久有效
        //editor.commit();
    }
}
